from mcstatus import JavaServer
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Server
from .forms import ServerForm
from django.http import Http404


# Create your views here.
def index(request):
    try:
        servers = Server.objects.all().filter(owner=request.user)
    except TypeError:
        return render(request, 'index_error.html')
    return render(request, 'index.html', {'servers': servers})

def check_user(request, server_id):
    server = Server.objects.get(id=server_id)
    if request.user != server.owner:
        raise Http404
@login_required(login_url='accounts:login')
def detail(request, server_id):
    server = Server.objects.get(id=server_id)
    check_user(request, server_id)
    try:
        status = JavaServer.lookup(server.ip + ":" + server.port).status()
    except:
        return render(request, 'detail_error.html', {'server': server})
    return render(request, 'detail.html', {'server': server, 'status': status})


@login_required(login_url='accounts:login')
def create(request):
    if request.method == 'POST':
        form = ServerForm(data=request.POST)
        if form.is_valid():
            server = form.save(commit=False)
            server.owner = request.user
            server.save()
            return redirect('mcserver_status:index')
    else:
        form = ServerForm()
    return render(request, 'create.html', {'form': form})


@login_required(login_url='accounts:login')
def delete(request, server_id):
    check_user(request, server_id)
    server = Server.objects.get(id=server_id)
    server.delete()
    return redirect('mcserver_status:index')


@login_required(login_url='accounts:login')
def update(request, server_id):
    check_user(request, server_id)
    server = Server.objects.get(id=server_id)
    if request.method == 'POST':
        form = ServerForm(data=request.POST, instance=server)
        if form.is_valid():
            form.save()
            return redirect('mcserver_status:index')
    else:
        form = ServerForm(instance=server)
    return render(request, 'update.html', {'form': form, 'server': server})
